// pages/storeDetail/storeDetail.js 
//引入模块
const MMS = require("../../utils/maxMonthSequence.js");
const {AddTrace} = require("../../utils/addCustTraceIns.js");
var app = getApp();
var self = "";
var shopId = "";
let officialDomain = app.globalData.officialDomain;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    storeData:{}, //店铺数据
    storeDisCountData:[], //店铺优惠数据
    watchTimes:0, //成功分享好友看过次数
    showModalStatus2: false, //菜品弹出层

    // 转发弹出框
    actionSheetHidden1: true, //分享弹出框
    actionSheetHidden2: true, //分享生成长图弹出框
    actionSheetHidden3: true, //联系客服弹出框
    actionSheetHidden4: true, //扫码兑换弹出框

    imageGreensTitle: "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/imageGreensTitle.png",//菜品名字图片
    imageGreensPrice:"https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/imageGreensPrice.png", //菜品价格图片
    isShowAddPro:true, //显示增加到我的小程序提示
    isShowBackHome:false, //显示回到首页按钮

    canChangeCouponId:"", //获取需要兑换优惠券id
    couponCanList:[], //可使用优惠券列表

    mkNum: 3, //更多使用须知最大条数

    customIndoorDevice:[], //自定义和配置的服务设施
    specialDishes:[], //特色菜品

    drawerImgList:[], //弹出层图片列表
    shopCouponRuleList: [], //优惠券使用规则列表
    shopFeatures:[], //店铺标签

    currentShopImgIndex:0, //店铺当前图片轮播索引
    currentDishImgIndex: 0, //店铺图片当前图片轮播索引
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      self = this;
      console.log(options)
      if (options.params){
          shopId = options.params; //店铺id
          this.initData(shopId);
          this.addScanTime(shopId); //增加店铺查看次数
          // 从转发和朋友圈而来
          if (options.isForward == 1) {
            this.setData({
              isShowBackHome: true
            })
            this.checkUserIdAsync((res) => {
              this.isForward(shopId, options.custId);
              this.getPointForward();
              AddTrace(officialDomain, { userId: res, shopId: shopId, cPage: "店铺详情页", cOper: "从转发和朋友圈来进入", cNote:"店铺详情页用户来源埋点"});
            })
          // 从首页及其其他页面进入
          }else if(options.isForward == 2){
              // 从优惠券列表过来，显示优惠券
              if (options.showActionSheet4 == "show"){
                  this.data.canChangeCouponId = options.couponId;
                  this.actionSheetTap4();
              }
            AddTrace(officialDomain, { userId: wx.getStorageSync("userId"), shopId: shopId, cPage: "店铺详情页", cOper: "从首页及其他页面进入", cNote: "店铺详情页用户来源埋点" });
          // 从公众号和桌角二维码而来
          }else{
            this.setData({
              isShowBackHome: true
            });
            this.checkUserIdAsync((res) => {
              this.getPointForward();
              AddTrace(officialDomain, { userId: res, shopId: shopId, cPage: "店铺详情页", cOper: "从公众号和桌角二维码进入", cNote: "店铺详情页用户来源埋点" });
            })
          }
      }

      // 顶部导航高度
      this.setData({
        topTitleHeight: app.globalData.topTitleHeight + 8
      })

      // 隐藏增加到我的小程序提示
      setTimeout(() => {
        this.setData({
          isShowAddPro: false
        })
      }, 3000)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkUserIdAsync((res) => {
      this.getPoint();
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
	

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // console.log(res)
    if (res.from === 'button') {
      // 来自页面内转发按钮
      // console.log(res.target)
      //点击转发增加商铺时客户分享记录
      this.custShareInfo();
    }
    if (this.data.storeData.shareImagePath && this.data.storeData.shareTitle){
      setTimeout(()=>{
        wx.pageScrollTo({
          scrollTop: 0,
        });   
        self.actionSheetbindchange();
      },500)
      return {
        title: this.data.storeData.shareTitle,
        path: '/pages/storeDetail/storeDetail?params=' + shopId + '&isForward=1&custId=' + wx.getStorageSync("userId"),
        imageUrl: this.data.storeData.shareImagePath + "?x-oss-process=image/format,jpg/interlace,1/resize,m_lfit,w_300,h_240",      
      }
    }else{
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
        });
        self.actionSheetbindchange();
      }, 500)
      return {
        path: '/pages/storeDetail/storeDetail?params=' + shopId + '&isForward=1&custId=' + wx.getStorageSync("userId"),
      }
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    self.getPoint();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 10000)
  },

  //check并异步存储获取用户id
  checkUserIdAsync(resolve){
    if (app) {
      app.checkLogin().then((res) => {
        // console.log(res);
        resolve(res);
      }).catch((error) => {
        // console.log(error);
        reject();
      })
    }
  },

  //初始化数据
  initData(e){
    // 初始化店铺数据
    wx.request({
      url: officialDomain + 'shopInfo/getShopInfo',
      data:{shopId:e},
      success:function(res){
        // console.log(res)
        // console.log(res.data.data)
        if (res.data.data && res.data.errorCode == "0000"){
          var resData = res.data.data;
          // console.log(resData.introImages)
          resData.shopAddress = resData.shopAddress ? resData.shopAddress.split(";") : []; //餐厅地址
          resData.contactWay = resData.contactWay ? resData.contactWay.split(";") : []; //联系方式
          resData.warmPrompt = resData.warmPrompt ? resData.warmPrompt.split(";") : []; //温馨提示
          resData.shopIntro = resData.shopIntro ? resData.shopIntro.split(";") : []; //餐厅介绍
          try {
            // console.log(JSON.parse(resData.openTime));
            resData.openTimeArray = [];
            JSON.parse(resData.openTime).forEach((item,index)=>{
              var openTimeObj = {};
              openTimeObj.shopOpenTimes = item.shopOpenTimes;
              openTimeObj.openTimeMonth = (typeof (item)) == "object" ? MMS.maxMonthSequence(item.shopOpenDateIds) : "";  //营业时间
              resData.openTimeArray.push(openTimeObj);
            })

          } catch (e) {
            resData.openTimeArray = [];
          } 

          console.log(resData.openTimeArray)         

          resData.heightTime =  resData.heightTime ? resData.heightTime.split(";") : [];//用餐高峰
          resData.flowContent = resData.flowContent ? resData.flowContent.split(";") : []; //特色介绍
          resData.shopImage = JSON.parse(resData.shopImage) ? JSON.parse(resData.shopImage) : []; //店铺图片
          
          // console.log(resData)
          self.setData({
            storeData:resData,
          })
        }else{
          wx.switchTab({
            url: '../index/index',
            duration:3000,
            success: function () {
              wx.showToast({
                icon: 'none',
                title: '此店铺已下架!',
              })
            }
          })
        }
      }
    })
     
    // 初始化店铺活动数据
    this.getShopIdfindCoupon(e);
    // 初始化店铺服务设置
    this.getShopLabel(e);
    // 初始化店铺菜品
    this.findShopDishes(e);
    // 初始化优惠券使用规则
    this.getShopCouponRule(e);

  },
// 初始化店铺活动数据
  getShopIdfindCoupon(e){
    wx.request({
      url: officialDomain + 'shopInfo/getShopIdfindCoupon',
      data: { shopId: e },
      success: function (res) {
        var data = res.data;
        if (data.errorCode = "0000") {
          self.setData({
            storeDisCountData: data.data
          })
        }
      }
    })
  },
// 初始化店铺服务设置
  getShopLabel(e){
    wx.request({
      url: officialDomain + 'shopInfo/getShopLabel',
      data: { shopId: e },
      success: function (res) {
        if(res.data.data.length && res.data.errorCode == "0000"){
          var customIndoorDevice = [];
          var shopFeatures = [];
          res.data.data.map((item,index)=>{
            if (item.relationType == "0" || item.relationType == "1"){
               customIndoorDevice.push(item);
            }else{
              shopFeatures.push(item);
            }
          })
          self.setData({
            customIndoorDevice: customIndoorDevice,
            shopFeatures: shopFeatures,
          })
        }
      }
    })
  },

  //初始化店铺菜品
  findShopDishes(e){
    wx.request({
      url: officialDomain + 'shopInfo/findShopDishes',
      data: { shopId: shopId, custId: wx.getStorageSync("userId")},
      success: function (res) {
        if (res.data.data.length && res.data.errorCode == "0000") {
          var resData = res.data.data;
          resData.map((item,index)=>{
            try{
              var dishImages = JSON.parse(item.dishImages);
              item.dishImages = dishImages;
              dishImages.map((dishItem, dishIndex) => {
                if (dishItem.isPriamry) {
                  item.priamryImagePath = dishItem.imagePath;
                }
              })
            }catch(error){
              item.dishImages = [];
              item.priamryImagePath = "";
            }
            return item;
          })
          self.setData({
            specialDishes: resData
          })

        }
      }
    })
  },

  //初始化优惠券使用规则
  getShopCouponRule(e){
    wx.request({
      url: officialDomain + '/shopInfo/getShopCouponRule',
      data: { shopId: e },
      success: function (res) {
        if(res.data.data.length && res.data.errorCode == "0000"){
          self.setData({
            shopCouponRuleList: res.data.data
          })
        }
      }
    })
  },

  //查询该用户当前所在店铺的积分
  getPoint: function () {
    wx.request({
      url: officialDomain + 'UserPoint/getPoint',
      data: { shopId: shopId, custId: wx.getStorageSync("userId"), },
      success: function (res) {
        // console.log(res)
        var data = res.data;
        if (data.errorCode = "0000") {
          if (data.data){ 
            self.setData({
              watchTimes: data.data.pointNumber - data.data.pointSub,
            })            
            var watchTimes = data.data.pointNumber - data.data.pointSub;
          }else{
            var watchTimes = 0;
          }
          //获取可以使用的优惠券数组  
          self.data.couponCanList = [];
          self.data.storeDisCountData.forEach((item, index) => {
              var objItem = {};
              if (watchTimes >= item.exchangeTimes && item.couponType == 0){
              // 代金券可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon11.png";
              } else if (watchTimes < item.exchangeTimes && item.couponType == 0){
                // 代金券不可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon10.png";
              } else if (watchTimes >= item.exchangeTimes && item.couponType == 1) {
                // 折扣券可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon21.png";
              } else if (watchTimes < item.exchangeTimes && item.couponType == 1) {
                // 折扣券不可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon20.png";
              } else if (watchTimes >= item.exchangeTimes && item.couponType == 2 ) {
                // 赠品券可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon31.png";
              } else if (watchTimes < item.exchangeTimes && item.couponType == 2 ) {
                // 赠品券不可兑换
                objItem.couponBgiName = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/canDaiJinCoupon30.png";
              }
              Object.assign(objItem, item);
              self.data.couponCanList.push(objItem);
          })
          self.setData({
            couponCanList: self.data.couponCanList
          }) 

        }
      },
      complete:function(res){
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    })
  },

  //查询该用户当前所在店铺的积分 如果pointNumber  = 0 或者 为null,增加一点积分
  getPointForward: function () {
    var data = { shopId: shopId, custId: wx.getStorageSync("userId") };
    wx.request({
      url: officialDomain + 'UserPoint/getPoint',
      data: data,
      success: function (res) {
        var data = res.data;
        // console.log(data)
        // pointNumber 为0 ,data.data为null ,加积分
        if (data.data){
          if (data.data.pointNumber == 0){
              self.addPoint(1);
              self.getPoint();
            }
        }else{
            self.addPoint(1);
            self.getPoint();
        }
      }
    })
  },

  // 来自转发isForward，check积点信息
  isForward(e,custId){
    // check积点信息
    if (custId == wx.getStorageSync("userId")){
        return;
    }
    var checkData = {
      custId: custId,
      shopId: e,
      childId: wx.getStorageSync("userId"),
    }
    // console.log(checkData)
    wx.request({
      url: officialDomain + 'UserPoint/checkPointInfo',
      method:"get",
      data: checkData,
      success: function (res) {
        // console.log(res)
        var data = res.data;
        if (data.errorCode = "0000" && data.data == 1) {
          self.addCheckPointInfo(checkData);
        }
      }
    })
  },

  //增加成功分享次数
  addCheckPointInfo(checkData){
    wx.request({
      url: officialDomain + 'UserPoint/addCheckPointInfo',
      method: "get",
      data: checkData,
      success: function (res) {
        // console.log(res)
      }
    })
  },

  // 判断是否重置加5积分
  judgeAddFivePoint(){
    wx.request({
      url: officialDomain + 'custShare/checkShareStatue',
      data: { shopId: shopId, custId: wx.getStorageSync("userId"), shareStyle:"A04" },
      success: function (res) {
        // console.log(res)
        var data = res.data;
        if(data.data == "1"){
            // 保存长图发送到朋友圈增加5个发现
            self.insCustShareInfo();
            self.addPoint(5);
        }
      }
    })
  },

  //插入用户保存长图记录
  insCustShareInfo(){
    wx.request({
      url: officialDomain + 'custShare/insCustShareInfo',
      data: { shopId: shopId, custId: wx.getStorageSync("userId"), shareStyle: "A04" },
      success: function (res) {
        // console.log(res)
      }
    })
  },

  //增加用户积分	
  addPoint(point){
    if (!point){
      return;
    }
    var data = {
      custId: wx.getStorageSync("userId"),
      shopId: shopId,
      pointNum: point
    }
    wx.request({
      url: officialDomain + 'UserPoint/addPoint',
      method: "get",
      data: data,
      success: function (res) {
        // console.log(res)
      }
    })
  },


  //增加查看次数addScanTime
  addScanTime:function(e){
    // 初始化店铺活动数据
    wx.request({
      url: officialDomain + 'shopInfo/addScanTime',
      data: { shopId: e, scanNum: 1},
      success: function (res) {
        // console.log(res)
        var data = res.data;
        if (data.errorCode = "0000") {
        }
      }
    })

  },


  //点击转发增加商铺时客户分享记录
  custShareInfo:function(){
    wx.request({
      url: officialDomain + '/custShare/custShareInfo',
      data: { shopId: shopId, custId: wx.getStorageSync("userId") },
      success: function (res) {
        // console.log("/custShare/custShareInfo")
        // console.log(res)
        var data = res.data;
      }
    })
  },

  
  // 商家客服
  shopCall: function () {
    wx.makePhoneCall({
      phoneNumber: self.data.storeData.contactWay[0]
    })
  },

  // 电话客服
  helpCall: function () {
    wx.makePhoneCall({
      phoneNumber: "604-370-5100",
      complete:function(res){
        self.actionSheetTap3();
      }
    })
  }, 

  //选择地址
  selectAddr:function(){
    if (self.data.storeData.longitude && self.data.storeData.latitude){
      wx.openLocation({
        latitude: Number(self.data.storeData.latitude),
        longitude: Number(self.data.storeData.longitude),
        scale: 13,
        name: self.data.storeData.shopName,
        address: self.data.storeData.shopAddress.join(";"),
      })     
    }else{
      wx.showToast({
        title: '店铺经纬度信息尚未完善',
        icon: "none",
        duration:3000,
      })
    }
  },

  //跳转页面
  // 通过data-params带上路径
  toOpen(e) {
    var item = e.currentTarget.dataset.params;
    wx.navigateTo({
      url: '../' + item + '/' + item + "?shopId=" + shopId
    })
  },

  //跳转web-view页面
  toOpenWebView(e) {
    var item = e.currentTarget.dataset.params;
    if (e.currentTarget.dataset.articleurl){
      wx.navigateTo({
        url: '../' + item + '/' + item + "?articleUrl=" + e.currentTarget.dataset.articleurl
      })
    }else{
      wx.showToast({
        title: '暂无更多介绍！',
        icon: "none"
      })
    }
  },
  //回到首页
  backHome(){
    wx.switchTab({
      url: '../index/index',
    })
    //回到首页按钮埋点
    AddTrace(officialDomain, {userId: wx.getStorageSync("userId"), shopId: shopId, cPage: "店铺详情页", cOper: "回到首页按钮被点击", cNote: "回到首页按钮埋点" });
  },

  // 菜品轮播图弹出显示
  powerDrawer2: function (e) {
    // console.log(e)
    var currentStatu = e.currentTarget.dataset.statu;
    var imgItem = e.currentTarget.dataset.imgitem;
    this.util2(currentStatu, imgItem);
  },
  
  util2: function (currentStatu, imgItem) {
    // console.log(imgItem)
    // 显示 
    if (currentStatu == "open" && imgItem.dishImages.length) {
      this.setData(
        {
          showModalStatus2: true,
          drawerImgList: imgItem,
          currentDishImgIndex:0
        }
      );
    }      //关闭 
    else if (currentStatu == "close") {
      this.setData(
        {
          showModalStatus2: false,
          drawerImgList:[],
          currentDishImgIndex: 0
        }
      );
    }
  },

  //增加点赞
  addGoodNum:function(e){
    // console.log(e);
    var dish = e.currentTarget.dataset.dish;
    wx.request({
      url: officialDomain + 'dishGood/custDishGood',
      data: { custId: wx.getStorageSync("userId"), dishId: dish.dishId, shopId: shopId, },
      success: function (res) {
        // console.log(res)
        if (res.data.errorCode == "0000") {
          if(res.data.data){
            self.data.drawerImgList.goodStatus = 1;
            ++self.data.drawerImgList.goodNum;
          }else{
            self.data.drawerImgList.goodStatus = 0;
            self.data.drawerImgList.goodNum = --self.data.drawerImgList.goodNum < 0 ? 0 : self.data.drawerImgList.goodNum;
          }
          self.setData({
            drawerImgList: self.data.drawerImgList
          })
          // 初始化店铺菜品
          self.findShopDishes();
        }
      }
    })
  },

//店铺轮播图片切换设置当前图片索引
  storeDataChange:function(e){
    if (e.detail.source != "tourch"){
      this.setData({
        currentShopImgIndex: e.detail.current
      })
    }
    if (e.detail.source != "autoplay") {
      this.setData({
        currentShopImgIndex: e.detail.current
      })
    }

  },

  //店铺轮播菜品图片切换设置当前图片索引
  dishDataChange: function (e) {
    if (e.detail.source != "tourch") {
      this.setData({
        currentDishImgIndex: e.detail.current
      })
    }
    if (e.detail.source != "autoplay") {
      this.setData({
        currentDishImgIndex: e.detail.current
      })
    }

  },
  

// 转发弹出框v1.5
// 开启或关闭转发弹窗
  // 关闭所有弹窗口
  actionSheetbindchange: function () {
    this.setData({
      actionSheetHidden1: true,
      actionSheetHidden2: true,
      actionSheetHidden3: true,
      actionSheetHidden4: true
    })
  },

  actionSheetTap1: function (res) {
    this.setData({
      actionSheetHidden1: !this.data.actionSheetHidden1
    })
    if (res != "fromForwardGet"){
      // 发现 按钮点击总数埋点
      AddTrace(officialDomain, { userId: wx.getStorageSync("userId"), shopId: shopId, cPage: "店铺详情页", cOper: "店铺:" + self.data.storeData.longTitle + "【发现+】按钮被点击", cNote: "发现按钮点击埋点" });
    }
  },

// 开启生成长图转发到朋友圈
  actionSheetTap2: function (res) {
    var _this = this;
    var longBgi = "https://zhuanyoyo.oss-us-west-1.aliyuncs.com/customerApplet/storeDetail/saveLongImg.jpg" + '?x-oss-process=image/resize,m_mfit,w_450,h_638/format,jpg/interlace,1';
    var shareImagePath = _this.data.storeData.longImagePath + '?x-oss-process=image/resize,m_mfit,w_290,h_254/format,jpg/interlace,1';
    var longTitle = _this.data.storeData.longTitle;
    // 获取第一张优惠券数据
    var shareDiscountData = ""; 
    shareDiscountData = _this.data.storeData.longDescribe;	
    var getwxcode = officialDomain + "qrcode/roundcode?shopId=" + shopId + "&userId=" + wx.getStorageSync("userId") +"&width=300&isForward=1";
    wx.showToast({
      title: '长图生成中...',
      icon: "loading",
      mask:true,
      duration:60000
    })
    console.log(longBgi);
    console.log(shareImagePath);
    console.log(getwxcode);
    // 背景图下载
    wx.downloadFile({
      url: longBgi,
      success: function (sres) {
        console.log(sres + "我是背景长图");
        longBgi = sres.tempFilePath;
        // 转发图片下载
            wx.downloadFile({
              url: shareImagePath,
              success: function (sres) {
                console.log(sres + "我是转发图片");
                shareImagePath = sres.tempFilePath;
                // 二维码下载
                  wx.downloadFile({
                    url: getwxcode,
                    success: function (sres) {
                      console.log(sres + "我是二维码图片");
                      getwxcode = sres.tempFilePath;

                      _this.setData({
                        actionSheetHidden2: !_this.data.actionSheetHidden2,
                        actionSheetHidden1: !_this.data.actionSheetHidden1
                      })

                      setTimeout(() => {
                        var ctx = wx.createCanvasContext("myCanvas", this);
                        ctx.setFillStyle("#FFF");
                        // ctx.fillRect(40, 0, 187.5, 266); 
                        ctx.fillRect(56, 0, 262.5, 372.4); 
                        ctx.fillRect(56, 0, 262.5, 372.4); 
                        //制作背景板
                        ctx.drawImage(longBgi, 0, 0, 262.5, 372.4);
                        // 转发图片
                        ctx.drawImage(shareImagePath, 9.8, 28, 242.2, 212.8);
                        // 店铺名
                        ctx.setFontSize(12.6);
                        ctx.setFillStyle("#000");
                        ctx.textAlign = "center";
                        ctx.fillText(longTitle, 91, 266, 113.4); 
                        // 优惠券
                        ctx.setFontSize(8.4);
                        ctx.setFillStyle("#7a7a7a");
                        ctx.fillText(shareDiscountData, 91, 350, 151.2); 
                        // 二维码图片
                        ctx.drawImage(getwxcode, 189, 256.2, 58.8, 58.8);
                        // 遮住二维码文字
                        // ctx.setFillStyle('#FFF');
                        // ctx.fillRect(187.6, 310.8, 58.8, 9.8);

                        ctx.draw();

                        var uploadImgCtx = wx.createCanvasContext("uploadImg", this);
                        uploadImgCtx.setFillStyle("#FFF");
                        uploadImgCtx.fillRect(320, 0, 1500, 2128);
                        //制作背景板
                        uploadImgCtx.drawImage(longBgi, 0, 0, 1500, 2128);
                        // 转发图片
                        uploadImgCtx.drawImage(shareImagePath, 56, 160, 1384, 1215);
                        // 店铺名
                        uploadImgCtx.setFontSize(72);
                        uploadImgCtx.setFillStyle("#000");
                        uploadImgCtx.textAlign = "center";                   
                        uploadImgCtx.fillText(longTitle, 525, 1520, 650);   
                        // 优惠券
                        uploadImgCtx.setFontSize(48);
                        uploadImgCtx.setFillStyle("#7a7a7a");
                        uploadImgCtx.fillText(shareDiscountData, 525, 2000, 864);  
                        // uploadImgCtx.fillRect(525, 2000, 864, 56); 
                        // 二维码图片
                        uploadImgCtx.drawImage(getwxcode, 1080, 1464, 336, 336);
                        // 遮住二维码文字
                        // uploadImgCtx.setFillStyle('#FFF');
                        // uploadImgCtx.fillRect(1080, 1776, 336, 56);  

                        uploadImgCtx.draw();
                      },500)

              }, complete: function (fres) {
                wx.hideToast();
              }
            })

            }, complete: function (fres) {
            }, fail: function (err) {
              wx.hideToast();
            }
          })

      }, complete: function (fres) {
      }, fail: function (err) {
        wx.hideToast();
      }
      })

  },

  // check用户保存到相册权限
  checkWritePhotosAlbum: function () {
    var _this = this;
    wx.showToast({
      title: 'loading',
      icon: "loading",
      mask: true
    })
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用保存到相册
              _this.saveLongImg();
            }
          })
        }else{
          _this.saveLongImg();
        }
      },
      complete(res){
        wx.hideToast();
      }
    })

  },
  // 保存长图
  saveLongImg: function () {
    var _this = this;
    wx.showToast({
      title: '图片保存中...',
      icon: "loading",
      mask: true
    })
    // 判断是否重置加5积分
    self.judgeAddFivePoint();

    wx.canvasToTempFilePath({
      canvasId: 'uploadImg',
      x: 0,
      y: 0,
      width: 1500,
      height: 2128,
      destWidth: 750,
      destHeight: 1064,
      quality: 1,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            // console.log(res)
            _this.actionSheetbindchange();
            wx.showToast({
              title: '保存成功',
              duration:2000
            })
          },
          fail: function (res) {
            wx.hideToast();
          }

        })
      },
      fail: function (res) {
        wx.hideToast();
      },
      complete:function(res){
        wx.hideToast();
      }
    }, this)
  },

  // 转发弹出框v1.7
  // 开启或关闭联系客服弹窗口
  actionSheetTap3: function () {
    this.setData({
      actionSheetHidden3: !this.data.actionSheetHidden3
    })
  },
 // 隐藏增加到小程序提示
  hideAddPro:function(){
    this.setData({
      isShowAddPro: false
    })    
  },
// 跳转到使用指南
  useGaTaps:function(){
    wx.request({
      url: officialDomain + '/admin/helpWordPath',
      success: function (res) {
        // console.log(res)
        var data = res.data;
        if(data.errorCode == "0000" && data.data){
          wx.navigateTo({
            url: '../webView/webView?articleUrl=' + data.data
          })    
        }
      }
    })

  },

  //发现更多使用须知最多100条
  findMoreKnows: function () {
    this.setData({
      mkNum: 100,
      storeData: this.data.storeData
    })
  },

  // v1.1.0
  // 扫码兑换或者转发分享
    getCouponOrShare(e){
      var watchTimes = e.currentTarget.dataset.watchtimes;
      var exchangeTimes = e.currentTarget.dataset.exchangetimes;
      var couponId = e.currentTarget.dataset.couponid;
      if (watchTimes >= exchangeTimes){
        // 可扫码兑换
        if (couponId){
          this.data.canChangeCouponId = couponId;
          this.actionSheetTap4();
        }
      }else{
        // 可转发分享
        this.actionSheetTap1("fromForwardGet");
        // 分享获取按钮埋点
        AddTrace(officialDomain, { userId: wx.getStorageSync("userId"), shopId: shopId, cPage: "店铺详情页", cOper: "店铺:" + self.data.storeData.longTitle + " 分享获取按钮被点击", cNote: "分享获取按钮埋点" });       
      }
    },
    // 开启或关闭扫码兑换弹窗口
    actionSheetTap4: function () {
      this.setData({
        actionSheetHidden4: !this.data.actionSheetHidden4
      })
    },
  // 扫码兑换优惠券
  scanCode(e) {
    // 关闭弹出框
    var couponId = this.data.canChangeCouponId;
    wx.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        try {
          var shopIdArr = res.path.split("?")[1].split("=");
          if (shopIdArr[0] == "params" && shopIdArr[1] && couponId) {
            // 扫描到正确的二维码兑券
            if (shopId == shopIdArr[1]) {
              self.custChangeCoupon({ couponid: couponId });
            } else {
              wx.showToast({
                title: '未搜索到正确店家二维码！',
                icon: 'none',
                duration: 3000
              })
            }
          } else {
            wx.showToast({
              title: '未搜索到店家！',
              icon: 'none',
              duration: 3000
            })
          }
        } catch (error) {
          wx.showToast({
            title: '未搜索到店家！',
            icon: 'none',
            duration: 3000
          })
        }
      },
      complete: function (res) {

      }
    })
  },

  //兑换优惠券
  custChangeCoupon: function (paramsData) {
    var _this = this;
    // 初始化店铺活动数据
    var reqData = {
      shopId: shopId,
      custId: wx.getStorageSync("userId"),
      couponId: paramsData.couponid,
      formId:""
    }
    wx.showLoading({
      title: 'loading',
    })
    wx.request({
      url: officialDomain + 'changeCoupon/custChangeCoupon',
      data: reqData,
      success: function (res) {
        // console.log(res)
        var resData = res.data;
        if (resData.data) {
          if (resData.data.custCouponId) {
            // 重置页面
            self.getPoint(); //获取所有积分
            self.getShopIdfindCoupon(shopId);
            // 扫描到正确的二维码消券
            self.couponDestory(resData.data);
          } else {
            wx.showToast({
              title: "此优惠券不存在！",
              icon: "none",
            })
          }
        } else {
          wx.showToast({
            title: resData.errorMsg ? resData.errorMsg : "SERVER ERROR!",
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function (err) {
        wx.hideLoading();
      },
      complete: function (res) {
      }
    })
  },

  //扫描到正确的二维码消券
  couponDestory(couponIdObj) {
    wx.request({
      url: officialDomain + 'coupon/destroy',
      data: { userCouponId: couponIdObj.custCouponId },
      success: function (res) {
        // console.log(res.data)
        wx.hideLoading();
        if (res.data) {
          if (res.data.errorCode == "0000") {
              // 重置页面
              self.actionSheetTap4();
              self.toShowOpen("showScanCode", couponIdObj);
          } else {
              wx.showToast({
                title: res.data.errorMsg,
                duration: 3000,
                icon: "fail"
              })
          }
        } else {
          wx.showToast({
            title: "该优惠券不存在",
            duration: 3000,
            icon: "fail"
          })
        }
      },
      fail: function (err) {
        wx.hideLoading();
      },
    })
  },

  //跳转页面
  // 通过data-params带上路径
  toShowOpen(item, toShowData) {
    var sendData = JSON.stringify(toShowData);
    wx.navigateTo({
      url: '../' + item + '/' + item + "?sendData=" + sendData
    })
  },

  // 滚动高度
  onPageScroll: function (object) {
    // console.log(object)
    if (object.scrollTop >= "235") {
        // 设置店铺详情标题
        wx.setNavigationBarTitle({
          title: self.data.storeData.shopName || "转yoyo",
        })
    }else{
        wx.setNavigationBarTitle({
          title:"转yoyo",
        })      
    }
  },

})




